package cn.anc.aonicardv.net.upload;

import android.os.Handler;
import android.util.Log;

import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.util.Locale;

import cn.anc.aonicardv.util.EncrytUtils;
import cn.anc.aonicardv.util.LogUtil;
import cn.anc.httpcontrolutil.CarControl;

/**
 * Created by baobaoding on 2018/4/5.
 */

public class CustomFileUpload extends Thread {
    private File file = null;
    private String ip = null;
    private int port = -1;
    private String upload_uri = null;
    private String boundary = null;
    private Handler handler;
    private String footer = null;
    private boolean _run = true;

    public void stopThread(boolean run) {
        this._run = !run;
    }

    public CustomFileUpload(String _ip, int _port, String _upload_uri, File _file) {
        file = _file;
        ip = _ip;
        port = _port;
        upload_uri = _upload_uri;
        if (CarControl.DeviceInfo.chip.equals("LT")) {
            boundary = "--Boundary------------V2ymHFg03ehbqgZCaKO6jy";
            footer = "\r\n" + boundary + "\r\n";
        } else {
            boundary = "---------AAAABBBBCCCCFFFFHHHH---------";
            footer = "\r\n--" + boundary + "--\r\n";
        }

        handler = new Handler();
    }

    @Override
    public void run() {
        if (file == null) {
            Log.e("CustomFileUpload", "file is null");
            return;
        }
        if (!file.exists() || file.length() <= 0) {
            Log.e("CustomFileUpload", "invalid file");
            return;
        }
        String header;
        if (CarControl.DeviceInfo.chip.equals("MSTAR")) {
            header = String.format(Locale.getDefault(), "POST %s HTTP/1.1\r\n"
                            + "Accept: */*\r\n"
                            + "Host: %s:%d\r\n"
                            + "Accept-Language: zh-CN\r\n"
                            + "Connection: Keep-Alive\r\n"
                            + "Content-Type: %s; boundary=%s\r\n"
                            + "Content-Length: %d\r\n\r\n",
                    upload_uri,
                    ip,
                    port,
                    "multipart/form-data",
                    boundary,
                    file.length() + footer.length());
        } else {
            header = String.format(Locale.getDefault(), "POST %s HTTP/1.1\r\n"
                            + "Accept: */*\r\n"
                            + "Host: %s:%d\r\n"
                            + "Accept-Language: zh-CN\r\n"
                            + "Connection: Keep-Alive\r\n"
                            + "Content-Type: %s; boundary=%s\r\n"
                            + "Content-Length: %d\r\n\r\n",
                    upload_uri + EncrytUtils.getMd5ByFile(file).toUpperCase(),
                    ip,
                    port,
                    "multipart/form-data",
                    boundary,
                    file.length() + footer.length());

        }
        LogUtil.e("------", "-------------header---------:" + header);
        FileInputStream inputStream = null;
        OutputStream outputStream = null;
        Socket socket = null;
        try {
            Log.w("CustomFileUpload", "header: " + header);
            socket = new Socket(ip, port);
            outputStream = socket.getOutputStream();
            //send header
            outputStream.write(header.getBytes("utf-8"));

            int BUFFER_SIZE = 0x8000;
            byte[] buffer = new byte[BUFFER_SIZE];
            inputStream = new FileInputStream(file);
            int totalLen = 0;
            int len;
            if (file.length() / BUFFER_SIZE > 0) {
                while ((len = inputStream.read(buffer, 0, BUFFER_SIZE)) > 0 && _run) {
                    outputStream.write(buffer, 0, len);
                    totalLen += len;
                    final int finalTotalLen = totalLen;
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mUploadCallback != null)
                                mUploadCallback.onProgress(finalTotalLen, file.length());
                        }
                    });
                }
                if (_run) {
                    outputStream.write(footer.getBytes("utf-8"));
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            if (mUploadCallback != null)
                                mUploadCallback.onSuccess();
                        }
                    });
                    outputStream.flush();
                }

            }

        } catch (Exception ex) {
            if (mUploadCallback != null)
                mUploadCallback.onError(ex);
            Log.w("CustomFileUpload", "CustomFileUpload: " + ex.getMessage());
        } finally {
            try {
                if (inputStream != null) inputStream.close();
                if (outputStream != null) outputStream.close();
                if (socket != null) socket.close();
            } catch (Exception e) {
                //e.printStackTrace();
                Log.e("CustomFileUpload", e.getMessage());
            }
        }
    }

    private UploadSubscriber mUploadCallback;

    public void setUploadCallback(UploadSubscriber mUploadCallback) {
        this.mUploadCallback = mUploadCallback;
    }

}
